import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { WorkflowTemplate } from './schemas/workflow-template.schema';
import { CreateWorkflowTemplateDto } from './dto/create-workflow-template.dto';

@Injectable()
export class WorkflowTemplateService {
    constructor(
        @InjectModel(WorkflowTemplate.name)
        private workflowTemplateModel: Model<WorkflowTemplate>,
    ) { }

    async create(createDto: CreateWorkflowTemplateDto) {
        const template = new this.workflowTemplateModel(createDto);
        return template.save();
    }

    async findAll(query: {
        category?: string;
        tags?: string[];
        search?: string;
        page?: number;
        limit?: number;
        sort?: string;
    }) {
        const { category, tags, search, page = 1, limit = 10, sort = '-createdAt' } = query;

        const filter: any = { isActive: true };
        if (category) filter.category = category;
        if (tags?.length) filter.tags = { $all: tags };
        if (search) {
            filter.$text = { $search: search };
        }

        const total = await this.workflowTemplateModel.countDocuments(filter);
        const templates = await this.workflowTemplateModel
            .find(filter)
            .sort(sort)
            .skip((page - 1) * limit)
            .limit(limit)
            .exec();

        return {
            templates,
            pagination: {
                total,
                page,
                limit,
                pages: Math.ceil(total / limit)
            }
        };
    }

    async findOne(id: string) {
        if (!Types.ObjectId.isValid(id)) {
            throw new BadRequestException('Invalid ID format');
        }

        const template = await this.workflowTemplateModel.findById(id);
        if (!template) {
            throw new NotFoundException(`Template with ID ${id} not found`);
        }
        return template;
    }

    async getCategories() {
        return this.workflowTemplateModel.distinct('category');
    }

    async incrementViews(id: string) {
        return this.workflowTemplateModel.findByIdAndUpdate(
            id,
            { $inc: { views: 1 } },
            { new: true }
        );
    }

    async toggleLike(id: string) {
        return this.workflowTemplateModel.findByIdAndUpdate(
            id,
            { $inc: { likes: 1 } },
            { new: true }
        );
    }

    async update(id: string, updateDto: Partial<CreateWorkflowTemplateDto>) {
        if (!Types.ObjectId.isValid(id)) {
            throw new BadRequestException('Invalid ID format');
        }

        const template = await this.workflowTemplateModel
            .findByIdAndUpdate(id, updateDto, { new: true });

        if (!template) {
            throw new NotFoundException(`Template with ID ${id} not found`);
        }
        return template;
    }

    async remove(id: string) {
        if (!Types.ObjectId.isValid(id)) {
            throw new BadRequestException('Invalid ID format');
        }

        const template = await this.workflowTemplateModel.findByIdAndDelete(id);
        if (!template) {
            throw new NotFoundException(`Template with ID ${id} not found`);
        }
        return template;
    }
} 